//
//  MeatShopViewController.m
//  PigMarket
//
//  Created by 张敬 on 2019/7/19.
//  Copyright © 2019年 pigmarket.oc. All rights reserved.
//

#import "MeatShopViewController.h"
#import "MeatPayViewController.h"
#import "MeatOrderViewController.h"
#import "MeatMessageViewController.h"


#import "MeatShopRightSideCell.h"
#import "MeatShopLeftSideCell.h"
#import "UITableView+FDTemplateLayoutCell.h"

#import "MeatShopBottomer.h"
#import "MeatShopCloseView.h"


#import "AddShoppingCartAnimationTool.h"
#import "MeatShopSectionModel.h"
#import "MeatShopRightModel.h"
#import "MeatShopCartBox.h"

#import "MeatMarketApi.h"


#define leftCellIdentifier @"leftCellIdentifier"
#define rightCellIdentifier @"rightCellIdentifier"

@interface MeatShopViewController ()<UITableViewDataSource, UITableViewDelegate, MeatShopCellDelegate>

@property (nonatomic, strong) UITableView *leftTableView;
@property (nonatomic, strong) UITableView *rightTableView;

@property (nonatomic, strong) MeatShopBottomer *bottomer;
@property (nonatomic, strong) MeatShopCartBox *aimsbox;
@property (nonatomic, strong) MeatShopCloseView *closeView;


@property (nonatomic, strong) MeatMarketApi *meatApi;
@property (nonatomic, strong) PigTypeListModel *model;
@property (nonatomic, strong) PigTypeModel *cartModel;

@property (nonatomic, strong) NSMutableArray *cartIds;

@property (nonatomic, assign) float aimPrice;

@property (nonatomic, assign) BOOL isShowBox;

@property (nonatomic, assign) NSInteger currentShopCartTotalNumbar;

@property (nonatomic) NSInteger currentLeftSideSectionValue; // 当前左边tableView选中的row值
@property (nonatomic) BOOL isInSelectedAnimationDuration;    // 是否正处于选中过程的动画当中

@end

@implementation MeatShopViewController

- (void)setupUI
{
    self.currentLeftSideSectionValue = 0;
    self.currentShopCartTotalNumbar = 0;
    self.isShowBox = YES;
    self.baseNavView.hidden = YES;
    self.aimPrice = 0.00;
    
    self.view.backgroundColor = mBackgroudColor;
    
    [self.view addSubview:self.closeView];
    [self.view addSubview:self.leftTableView];
    [self.view addSubview:self.rightTableView];
    [self.view addSubview:self.bottomer];
    
    [self.rightTableView addObserver:self
                          forKeyPath:@"contentOffset"
                             options:NSKeyValueObservingOptionNew
                             context:nil];
    
}


- (void)setupLayout
{
    
    {
        self.reloadBtn.mj_y -= 100;
        self.reloadLab.mj_y -= 100;
    }
    
    
    {
        CGFloat h = KScreenHeight - (TJ_MeatShop_Header + _bottomer.height + 52);
        _rightTableView.height = _leftTableView.height = h;
        _rightTableView.height += 10;
        _bottomer.mj_y = self.leftTableView.bottom;
    }
    
    {
        _closeView.mj_y = (_rightTableView.height - _closeView.height)/2.0 - 20;
    }
}


- (void)initData {
    [self obtainCartData];
}

- (void)refresh{
    
    if (self.refreshBlock) {
        self.refreshBlock(0);
    }
    
    [self initData];
}

- (void)obtainShopListData{
    
    @weakify(self);
    [[self.meatApi getBuyMeatPigTypeListByShopId:self.shopId] subscribeNext:^(PigTypeListModel * _Nullable model) {
        @strongify(self);
        
        if (model.list.count >0) {
            
            __block float price = 0.00;
            [model.list enumerateObjectsUsingBlock:^(PigTypeModel * _Nonnull typeModel, NSUInteger idx, BOOL * _Nonnull stop) {
               
               __block NSInteger number = 0;
                [typeModel.list enumerateObjectsUsingBlock:^(PigTypeItem * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                    
                    [self.cartModel.list enumerateObjectsUsingBlock:^(PigTypeItem * _Nonnull item, NSUInteger idx, BOOL * _Nonnull stop) {
                       
                        if ([obj.advanceSaleId isEqual:item.advanceSaleId] ) {
                            obj.isChicked = YES;
                            number ++;
                            price += [obj.nowPrice floatValue];
                        }
                    }];
                    
                    typeModel.totalNumber = number;

                }];
            }];
            
            self.model = model;
            self.model.price = price;
            self.bottomer.price = price;
            
            [self haveData];
            [self.leftTableView reloadData];
            [self.rightTableView reloadData];
            
        }else{
            [self noData];
            self.reloadBtn.hidden = YES;
            self.closeView.hidden = NO;
        }
        
    } error:^(NSError * _Nullable error) {
        @strongify(self);
        [self noData];
        [self loadErrorData];
    }];

}

//获取店内购物车数据
- (void)obtainCartData {
    
    @weakify(self);
    [[self.meatApi getBuyMeatCartListByShopId:self.shopId] subscribeNext:^(PigTypeModel * _Nullable model) {
        @strongify(self);
        self.cartModel = model;
        self.aimsbox.model = model;
        
        if (self.cartIds.count >0) {
            [self.cartIds removeAllObjects];
        }
        
        [model.list enumerateObjectsUsingBlock:^(PigTypeItem * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            [self.cartIds addObject:obj.shoppingCartId];
        }];
        
        if (self.cartModel.list.count <= 0) {
            [self.bottomer.cartIcon setImage:[UIImage imageNamed:@"meat_shop_cart_gray"]];
            self.bottomer.cartTipNumberLab.hidden = YES;
            
        }else{
            [self.bottomer.cartIcon setImage:[UIImage imageNamed:@"meat_shop_cart_light"]];
            self.bottomer.cartTipNumberLab.text = [NSString stringWithFormat:@"%@", @(self.cartModel.list.count)];
            self.bottomer.cartTipNumberLab.hidden = NO;
        }
        
        [self obtainShopListData];

    }error:^(NSError * _Nullable error) {
        @strongify(self);
        [self noData];
        [self loadErrorData];
    }];
}


//添加购物车
- (void)addCartDataBySaleId:(NSNumber *)saleId{
    
    @weakify(self);
    [[self.meatApi getMeatAddCartByShopId:self.shopId advanceSaleId:saleId] subscribeNext:^(NSNull * _Nullable x) {
        @strongify(self);
        [self initData];
    }error:^(NSError * _Nullable error) {
        [self showHudWithMsg:@"添加购物车失败"];
        
    }];
}

//删除购物车数据
- (void)deleteCartDataBySaleId:(NSArray *)saleId{
    
    @weakify(self);
    [[self.meatApi getMyMeatDeleteCartByIds:saleId] subscribeNext:^(NSNull * _Nullable x) {
        @strongify(self);
        [self initData];
        
    }error:^(NSError * _Nullable error) {
        [self showHudWithMsg:@"删除购物车失败"];
    }];
}

#pragma mark - ScrollViewDelegate

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    
    if ([scrollView isEqual:self.rightTableView] && self.isInSelectedAnimationDuration == NO) {
        
        NSInteger section = [self.rightTableView indexPathForCell:self.rightTableView.visibleCells.firstObject].section;
        if (self.currentLeftSideSectionValue != section) {
            
            self.currentLeftSideSectionValue = section;
            NSInteger newSelectedIndex = section;
            
            [self.leftTableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:newSelectedIndex inSection:0]
                                      atScrollPosition:UITableViewScrollPositionMiddle
                                              animated:YES];
            [self.leftTableView reloadData];
        }
    }
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    
    if ([scrollView isEqual:self.rightTableView]) {
       self.isInSelectedAnimationDuration = NO;
    }
}


- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView {
    
    if ([scrollView isEqual:self.rightTableView]) {
        self.isInSelectedAnimationDuration = NO;
    }
}


#pragma mark - 折叠按钮点击代理

- (void)clickFoldLabel:(MeatShopRightSideCell *)cell{
    
    NSIndexPath *indexPath = [self.rightTableView indexPathForCell:cell];
    
    PigTypeModel *sectionModel = self.model.list[indexPath.section];
    PigTypeItem *model = sectionModel.list[indexPath.row];
    model.isOpening= !model.isOpening;
    [self.rightTableView beginUpdates];
    [self.rightTableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    [self.rightTableView endUpdates];
}


//设置cell高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == self.leftTableView) {
        return 46;
    }
    
    PigTypeModel *sectionModel = self.model.list[indexPath.section];
    if (sectionModel.list.count > 0)
    {
        PigTypeItem *model = sectionModel.list[indexPath.row];
        
        if (model.isOpening) {
            // 使用不缓存的方式
            return [self.rightTableView fd_heightForCellWithIdentifier:rightCellIdentifier configuration:^(id cell) {

                [self handleCellHeightWithNewsCell:cell indexPath:indexPath];
            }];
        }else{
            // 使用缓存的方式
            return [self.rightTableView fd_heightForCellWithIdentifier:rightCellIdentifier cacheByIndexPath:indexPath configuration:^(id cell) {

                [self handleCellHeightWithNewsCell:cell indexPath:indexPath];
            }];
        }
    } else{

        return 10;
    }
}


// 处理折叠cell高度
- (void)handleCellHeightWithNewsCell:(id)cell indexPath:(NSIndexPath *)indexPath{
    
    MeatShopRightSideCell *newsCell = (MeatShopRightSideCell *)cell;
    PigTypeModel *sectionModel = self.model.list[indexPath.section];
    newsCell.model = sectionModel.list[indexPath.row];
}


#pragma mark - UITableView.delegate

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    if (tableView == self.leftTableView) {
        return self.model.list.count;
    }

    PigTypeModel *typeModel = self.model.list[section];
    return typeModel.list.count;
}


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    if (tableView == self.leftTableView) {
        return 1;
    }
    return self.model.list.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    // 左边的cell
    if (tableView == self.leftTableView) {
        MeatShopLeftSideCell *cell = [tableView dequeueReusableCellWithIdentifier:leftCellIdentifier forIndexPath:indexPath];
        
        PigTypeModel *typeModel = self.model.list[indexPath.row];
        cell.pigPartsLab.text = typeModel.positionName.length >0 ?typeModel.positionName :typeModel.typeName;
        
        if (self.currentLeftSideSectionValue == indexPath.row) {
            [cell updateToSelectedStateAnimated:YES];
        }else{
            [cell updateToNormalStateAnimated:YES];
        }
        
        if (typeModel.totalNumber>0) {
            cell.shopCartTipNumber.hidden = NO;
            cell.shopCartTipNumber.text = [NSString stringWithFormat:@"%ld", (long)typeModel.totalNumber];
        }else{
            cell.shopCartTipNumber.hidden = YES;
        }
        
        return cell ;
    } else {
        
        MeatShopRightSideCell *newsCell = [tableView dequeueReusableCellWithIdentifier:rightCellIdentifier];
        newsCell.cellDelegate = self;
        
        PigTypeModel *sectionModel = self.model.list[indexPath.section];
        PigTypeItem *model = sectionModel.list[indexPath.row];
        newsCell.model = model;
        
        @weakify(self);
        newsCell.shopCartBlock = ^(UIButton *btn) {
            @strongify(self);

            model.isChicked = YES;

            [self addCartDataBySaleId:model.advanceSaleId];
            
            self.currentLeftSideSectionValue = indexPath.section;
            self.currentShopCartTotalNumbar++;
            sectionModel.totalNumber++;

            [[AddShoppingCartAnimationTool shareTool] startAnimationandFromView:btn toView:self.bottomer.cartIcon imgView:nil];

            if (self.currentShopCartTotalNumbar>0) {

                self.bottomer.cartTipNumberLab.hidden = NO;
                self.bottomer.cartTipNumberLab.text = [NSString stringWithFormat:@"%ld", (long)self.currentShopCartTotalNumbar];
            }

//            if (sectionModel.totalNumber>0) {
//                cell.shopCartTipNumber.hidden = NO;
//                cell.shopCartTipNumber.text = [NSString stringWithFormat:@"%ld", (long)sectionModel.totalNumber];
//                self.bottomer.cartIcon.image = [UIImage imageNamed:@"meat_shop_cart_light"];
//            }

            [self.rightTableView reloadData];
        };

        return newsCell;
    }
    return [UITableViewCell new];
}


- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{

    if (tableView == self.rightTableView && section <self.model.list.count) {

        UIView *view = [UIView new];
        view.frame = CGRectMake(0, 0, KScreenWidth, 30);
        view.backgroundColor = mBackgroudColor;

        UILabel *label = [UILabel new];
        label.textColor = UIColorFromRGB(0x262626);
        label.font = mMediumFont(16);
        label.frame = CGRectMake(15, 0, KScreenWidth - 10, 30);

        PigTypeModel *typeModel = self.model.list[section];
        label.text = typeModel.positionName.length >0 ?typeModel.positionName :typeModel.typeName;

        [view addSubview:label];
        return view;
    }
    return nil;
}


- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return [tableView isEqual:self.rightTableView]?30 :0.01;
}


#pragma mark  - 点击 cell 的代理方法

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    // 右边tableView正在滑动而此时正在点击左边tableView的cell
    if ([tableView isEqual:self.leftTableView] && self.rightTableView.isDecelerating && self.rightTableView.isDragging) {
        
        [self.rightTableView setContentOffset:self.rightTableView.contentOffset animated:NO];
        [self.leftTableView setContentOffset:self.leftTableView.contentOffset animated:NO];
        return;
    }
    
    if ([tableView isEqual:self.leftTableView]) {
        
        NSInteger oldSelectedIndex = self.currentLeftSideSectionValue;
        NSInteger newSelectedIndex = indexPath.row;
        self.currentLeftSideSectionValue = newSelectedIndex;
        
        [self.leftTableView reloadData];
        
        // 重复点击同一个cell无效
        if (oldSelectedIndex == newSelectedIndex) {
            return;
        }
        
        self.isInSelectedAnimationDuration = YES;
        [self.rightTableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:newSelectedIndex]
                                   atScrollPosition:UITableViewScrollPositionTop animated:YES];
        
        // 解决最后两个cell点击不移动时出现的bug
        [self performSelector:@selector(makeIsInSelectedAnimationDurationEquilNO) withObject:nil afterDelay:0.05f];
        
    } else {
        
    }
}


#pragma mark - setter and  getter
//- 左边的 tableView
- (UITableView *)leftTableView {
    
    if (!_leftTableView) {
        
        UITableView *tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 10, TJ_MeatShop_LeftSideWidth, 0)];
        [self.view addSubview:tableView];
        tableView.dataSource = self;
        tableView.delegate = self;
        tableView.backgroundColor = mBackgroudColor;
        tableView.separatorColor = KClearColor;
        [tableView registerClass:[MeatShopLeftSideCell class] forCellReuseIdentifier:leftCellIdentifier];
        if (@available(iOS 11.0, *)) {
            tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        }
        _leftTableView = tableView;
        _leftTableView.hidden = YES;
    }
    return _leftTableView;
}


// - 右边的 tableView
- (UITableView *)rightTableView {
    
    if (!_rightTableView) {
        
        UITableView *tableView = [[UITableView alloc] initWithFrame:CGRectMake(TJ_MeatShop_LeftSideWidth, 10, TJ_MeatShop_RightSideWidth, 0)];
        [self.view addSubview:tableView];
        tableView.dataSource = self;
        tableView.delegate = self;
        [tableView registerClass:[MeatShopRightSideCell class] forCellReuseIdentifier:rightCellIdentifier];
        tableView.backgroundColor = KWhiteColor;
        tableView.estimatedRowHeight = 0;
        tableView.estimatedSectionFooterHeight = 0;
        tableView.estimatedSectionHeaderHeight = 0;
        _rightTableView = tableView;
        _rightTableView.hidden = YES;
        if (@available(iOS 11.0, *)) {
            tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        }
    }
    return _rightTableView;
}


- (MeatShopBottomer *)bottomer
{
    if (!_bottomer) {
        _bottomer = [[MeatShopBottomer alloc] init];
        _bottomer.hidden = YES;
        _bottomer.price = self.model.price;
        
        @weakify(self);
        __block BOOL isOpen = NO;
        _bottomer.dealShowCartBlock = ^{
            @strongify(self);
            
            isOpen = !isOpen;
            
#pragma mark - 此处有微小Bug
            if (self.cartModel.list.count >0) {
                if (isOpen) {
                    
                    MeatShopCartBox *box = [[MeatShopCartBox alloc] init];
                    box.model = self.cartModel;
                    self.aimsbox = box;
                    
                    //
                    box.dealDeleteCartBlock = ^(NSInteger params) {
                        
                        if (params == -1) {
                            [self deleteCartDataBySaleId:self.cartIds];
                        }else{
                            [self deleteCartDataBySaleId:@[@(params)]];
                        }
                    };
                    
                    //
                    box.dismissBlock = ^{
                        
                        self.bottomer.mj_y = self.leftTableView.bottom;
                        [self.view addSubview:self.bottomer];
                    };
                    [box showView];
                    
                    UIWindow *window = [[UIApplication sharedApplication] keyWindow];
                    self.bottomer.mj_y = KScreenHeight - self.bottomer.height;
                    [window addSubview:self.bottomer];
                    
                }else{
                    
                    [kNotificationCenter postNotificationName:KMeatMarketCartBoxHiddenNotification object:nil];
                }
            }else{
                [self showHudWithMsg:@"购物车为空"];
            }
        };
        
        
#pragma mark - 支付
        _bottomer.dealPayBlock = ^{
            @strongify(self);
            if (self.shopId && self.model.price >0) {
                
                MeatOrderViewController *vc = [[MeatOrderViewController alloc] init];
                vc.shopId = self.shopId;
                vc.saleType = self.model.arrearsIf;
                [self.navigationController pushViewController:vc animated:YES];
            }else{
                [self showHudWithMsg:@"请添加商品到购物车"];
            }
        };
    }
    return _bottomer;
}


- (MeatShopCloseView *)closeView{
    
    if (!_closeView) {
        _closeView = [[MeatShopCloseView alloc] init];
        _closeView.hidden = YES;
        
        @weakify(self);
        _closeView.dealLeaveMessageBlock = ^{
            @strongify(self);
            MeatMessageViewController *vc = [[MeatMessageViewController alloc] init];
            vc.shopId = self.shopId;
            [self.navigationController pushViewController:vc animated:YES];
        };
    }
    return _closeView;
}


- (MeatMarketApi *)meatApi{
    
    if(!_meatApi){
        _meatApi = [[MeatMarketApi alloc]init];
    }
    return _meatApi;
}


- (PigTypeListModel *)model{
    
    if (!_model) {
        _model = [[PigTypeListModel alloc] init];
    }
    return _model;
}


- (PigTypeModel *)cartModel{
    
    if (!_cartModel) {
        _cartModel = [[PigTypeModel alloc] init];
    }
    return _cartModel;
}


- (NSMutableArray *)cartIds{
    
    if (!_cartIds) {
        _cartIds = [NSMutableArray array];
    }
    return _cartIds;
}


#pragma mark - Other

- (void)makeIsInSelectedAnimationDurationEquilNO {

    self.isInSelectedAnimationDuration = NO;
}

- (void)haveData{
    
    [super haveData];
    self.leftTableView.hidden = NO;
    self.rightTableView.hidden = NO;
    self.bottomer.hidden = NO;

}

- (void)noData{
    [super noData];
    self.leftTableView.hidden = YES;
    self.rightTableView.hidden = YES;
    self.bottomer.hidden = YES;
}

#pragma mark - System

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context {
    
    // 点击左侧tableView中的cell触发移动
    if (self.isInSelectedAnimationDuration == YES) {
        [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(makeIsInSelectedAnimationDurationEquilNO) object:nil];
    }
}

- (void)dealloc {
    
    [self.rightTableView removeObserver:self forKeyPath:@"contentOffset"];
}

@end
